#!/bin/bash
# 7Ji: this is a heavy hack. WeChat, for whatever reason, calls dde-file-manager -> nautilus -> dolphin for
#   any file that it wants to open, instead of a sane dbus call, or xdg-open.
#      Basically, we pretend to be dde-file-manager and hijack the whole call chain in the first place, and
#   convert the not-so-smart dde-file-manager call to a sane dbus-call, or xdg-open if that fails.

_show_item=''
_item=''
for _arg in "$@"; do
    if [[ "${_arg}" == --show-item ]]; then
        _show_item='y'
    else
        [[ -z "${_item}" ]] && _item="${_arg}"
    fi
done

if [[ "${_show_item}" ]]; then
    _path=$(readlink -f -- "${_item}") # Resolve this to absolute path that's same across host / guest
    echo "Fake deepin file manager: dbus-send to open '${_path}' in file manager" 
    if [[ -d "${_path}" ]]; then 
        # WeChat pass both files and folders in the same way, if we use ShowItems for folders, 
        # it would open that folder's parent folder, which is not right.
        _object=ShowFolders
        _target=folders
    else
        _object=ShowItems
        _target=items
    fi
    exec dbus-send --print-reply --dest=org.freedesktop.FileManager1 \
        /org/freedesktop/FileManager1 \
        org.freedesktop.FileManager1."${_object}" \
        array:string:"file://${_path}" \
        string:fake-dde-file-manager-show-"${_target}"
    # We should not fall to here, but add a fallback anyway
    echo "Fake deepin file manager: fallback: xdg-open to show '${_path}' in file manager"
    exec xdg-open "${_path}"
else
    echo "Fake deepin file manager: xdg-open with args $@"
    exec xdg-open "$@"
fi
# At this stage, it's either: dbus-send not found, or xdg-open not found, this should not happen
# In whatever case, bail out
echo "Fake deepin file manager: could not open any thing, original args: $@"
exit 1